package com.dmgis.hndz.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.dmgis.entity.ContourSetting;
import com.dmgis.hndz.common.constant.FileContentType;
import com.dmgis.hndz.common.utils.*;
import com.dmgis.hndz.mapper.Qxaa01aMapper;
import com.dmgis.hndz.mapper.RiskManagementMapper;
import com.dmgis.hndz.pojoVo.*;
import com.dmgis.hndz.sddz.dto.Ybba01bDTO;
import com.dmgis.hndz.sddz.service.Zdda01aService;
import com.dmgis.service.DmServiceConnector;
import com.google.common.primitives.Bytes;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.hndz.service.*;
import com.dmgis.hndz.pojo.*;
import com.dmgis.weblib.MapCommon;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Paths;


import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.dmgis.hndz.common.constant.FilePath.GEO_FAC;
import static com.dmgis.hndz.common.constant.FilePath.PRODUCT;


@Api("公共接口")
@RestController
@CrossOrigin
@RequestMapping("/common")
public class CommonController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private CollectConfigService collectConfigService;

    @Autowired
    private YqService yqService;

    @Autowired
    private TownshipStationService townshipStationService;

    @Autowired
    private SmallScaleStationService smallScaleStationService;

    @Autowired
    private JobMakeService jobMakeService;

    @Autowired
    private YbzzConfigService ybzzConfigService;

    @Autowired
    private GridAddNameService gridAddNameService;

    @Autowired
    private CommonService commonService;

    @Autowired
    private DqyjService dqyjService;

    @Autowired
    private YjfwService yjfwService;

    @Autowired
    private Ybba01bService ybba01bService;

    @Autowired
    private Ybba01cService ybba01cService;

    @Autowired
    private Ybba02bService ybba02bService;

    @Autowired
    private Ybba02cService ybba02cService;

    @Autowired
    private Ybba01aService ybba01aService;

    @Autowired
    private Ybba02aService ybba02aService;

    @Autowired
    private Ybca02aService ybca02aService;

    @Autowired
    private RiskManagementMapper riskManagementMapper;

    @Autowired
    private Qxaa01aMapper qxaa01aMapper;

    @Autowired
    private TxtFileManager txtFileManager;

    @Autowired
    private Qxda02aService qxda02aService;

    @Autowired
    private Qxdd01aService qxdd01aService;

    @Autowired
    private Zdda01aService zdda01aService;

    @Autowired
    private Ybab01aService ybab01aService;

    @Value("${dmgis.serveName}")
    private String serveName;

    @Value("${server.port}")
    private String txtPort;

    @Value("${dmgis.ip}")
    private String dmgisIp;

    @Value("${dmgis.port}")
    private String dmgisPort;

    @Autowired
    private MessageSendService messageSendService;

    @Autowired
    private Zhaa03bService zhaa03bService;

    private static final String pluginClassFullName = "service";

    private static final String methodName = "contour";

    @Value("${dmgis.rect}")
    private String rect;

    @Value("${filePath.txtFilePath}")
    private String txtFile;

    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${nginx.url}")
    private String nginxUrl;

    @Value("${nginx.filepath}")
    private String nginxFilepath;

    @Autowired
    private MinIOUtil minIOUtil;

    @ApiOperation("/获取配置")
    @GetMapping("/getSysConfig")
    private SysResult getSysConfig() {
        List<SysConfig> list = sysConfigService.getList1();
        return SysResult.success(list);
    }

    @ApiOperation("获取服务用语")
    @GetMapping("/getServiceLanguage")
    public SysResult getServiceLanguage() {
        List<SysConfig> serviceLanguage = sysConfigService.getServiceLanguage();
        return SysResult.success(serviceLanguage);
    }

    @ApiOperation("获取采集配置文件")
    @GetMapping("/getCollectConfig")
    public SysResult getCollectConfig() {
        List<CollectConfig> list = collectConfigService.getList();
        return SysResult.success(list);
    }

    @ApiOperation("获取乡镇站点数据")
    @GetMapping("/getTownshipStation")
    public SysResult getTownshipStation(@RequestParam("city") String city) {
        List<TownshipStation> list = townshipStationService.getList2(city);
        return SysResult.success(list);
    }

    @ApiOperation("获取区域自动站站点信息")
    @GetMapping("/getSmallScaleStation")
    public SysResult getSmallScaleStation(@RequestParam("city") String city) {
        List<SmallScaleStation> list = smallScaleStationService.getList6(city);
        return SysResult.success(list);
    }

    @ApiOperation("获取业务制作信息")
    @GetMapping("/getJobMake")
    public SysResult getJobMake() {
        List<JobMake> list = jobMakeService.getList1();
        return SysResult.success(list);
    }

    @ApiOperation("获取网格信息")
    @GetMapping("/getYbzzConfig")
    public SysResult getYbzzConfig() {
        List<YbzzConfig> list = ybzzConfigService.getList();
        return SysResult.success(list);
    }

    @ApiOperation("获取格点别名")
    @GetMapping("/getGridAddName")
    public SysResult getGridAddName() {
        List<GridAddName> list = gridAddNameService.getList();
        return SysResult.success(list);
    }

    @ApiOperation("更新配置")
    @PostMapping("/updateSysConfig")
    public SysResult updateSysConfig(@RequestBody SysConfig sysConfig) {
        Integer rows = sysConfigService.updateByParamName(sysConfig);
        return SysResult.success(rows);
    }

    @ApiOperation("获取文档产品的期数")
    @GetMapping("/getSysConfig1")
    public SysResult getSysConfig1(@RequestParam("paramName") String paramName) {
        List<SysConfig> list = sysConfigService.getSysConfig1("产品期数", paramName);
        return SysResult.success(list);
    }

    @ApiOperation("更新文档产品的期数")
    @PostMapping("/updateSysConfig1")
    public SysResult updateSysConfig2(@RequestBody SysConfig sysConfig) {
        Integer rows = sysConfigService.updateSysConfig2(sysConfig);
        return SysResult.success(rows);
    }

    @ApiOperation("保存文档产品期数")
    @PostMapping("/saveSysConfig")
    public SysResult saveSysConfig(@RequestBody SysConfig sysConfig) {
        Integer rows = sysConfigService.saveSysConfig(sysConfig);
        return SysResult.success(rows);
    }

    @ApiOperation("判断点是否在多边形内")
    @PostMapping("/inPolygon")
    public SysResult inPolygon(@RequestBody InPolygonDto inPolygonDto) {
        Boolean inPolygon = DmgisUtils.isScope(inPolygonDto.getMapPoint(), inPolygonDto.getPolygon());
        return SysResult.success(inPolygon);
    }

    @ApiOperation("多边形求中心点")
    @GetMapping("/getCenterPoint")
    public SysResult getCenterPoint(@RequestParam("pointStr") String pointStr) {
        String[] pointStrArr = pointStr.split(";");
        List<DmMapPoint> dmMapPointList = new ArrayList<>();
        for (String point : pointStrArr) {
            String[] pointString = point.split(",");
            DmMapPoint dmMapPoint = new DmMapPoint(Double.parseDouble(pointString[0]), Double.parseDouble(pointString[1]));
            dmMapPointList.add(dmMapPoint);
        }
        int[] pParts = new int[1];
        pParts[0] = dmMapPointList.size();
        MapCommon mapCommon = new MapCommon();
        DmMapPoint polygonCenterPoint = mapCommon.getPolygonCenterPoint(dmMapPointList.toArray(new DmMapPoint[dmMapPointList.size()]), pParts, 1);
        return SysResult.success(polygonCenterPoint);
    }

    @ApiOperation("兰伯特点集转换为经纬度点集")
    @GetMapping("/lbtToWgsPoints")
    public SysResult lbtToWgsPoints(@RequestParam("pointStr") String pointStr) {
        try {
            String[] pointStrArr = pointStr.split(";");
            List<DmMapPoint> pointList = new ArrayList<>();
            for (String point : pointStrArr) {
                String[] pointArr = point.split(" ");
                DmMapPoint dmMapPoint = DmgisUtils.lbtToWgs(Double.parseDouble(pointArr[0]), Double.parseDouble(pointArr[1]));
                pointList.add(dmMapPoint);
            }
            StringBuilder sb = new StringBuilder();
            for (DmMapPoint dmMapPoint : pointList) {
                sb.append(dmMapPoint.getX()).append(",").append(dmMapPoint.getY()).append(";");
            }
            sb.deleteCharAt(sb.lastIndexOf(";"));
            return SysResult.success(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return SysResult.fail("转换失败");
        }

    }

    @ApiOperation("获取预警内接口乡界面接口")
    @PostMapping("/getYjqCountry")
    public SysResult getYjqCountry(@RequestBody YjqQueryCountryDto yjqQueryCountryDto) {
        try {
            List<CountryVO> country = commonService.getCountry(yjqQueryCountryDto);
            return SysResult.success(country);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("查询预警区失败");
            return SysResult.fail("查询预警区失败");

        }
    }

    /**
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param yjLevel   预警等级 1：红色，2：橙色，3：黄色，4：蓝色
     * @param yjType    预警类型 1：国家级，2：省级，3：市级，4：县级
     * @param advcode   行政编码
     * @return
     */
    @ApiOperation("预警查询")
    @PostMapping("/getYj")
    public SysResult getYj(String startTime, String endTime, Integer yjType, Integer yjLevel, String advcode) {
        List<Ybba01bDTO> yj = new ArrayList<>();
        if (advcode == null) {
            return SysResult.fail("advcode不能为空");
        }
        // 省级账号
        if (advcode.endsWith("0000")) {
            // 查询全部
            if (yjType == null) {
                // 省级预警
                List<Ybba01bDTO> yjProvince = ybba01aService.getYj(startTime, endTime, yjLevel);
                // 市级预警
                List<Ybba01bDTO> yjCity = ybba01bService.getYj(startTime, endTime, yjLevel, null);
                // 县级预警
                List<Ybba01bDTO> yjCounty = ybba01cService.getYj(startTime, endTime, yjLevel, null);
                yj.addAll(yjProvince);
                yj.addAll(yjCity);
                yj.addAll(yjCounty);
            }
            // 查询省级预警
            else if (yjType == 2){
                yj = ybba01aService.getYj(startTime, endTime, yjLevel);
            }
            // 查询市级
            else if (yjType == 3) {
                yj = ybba01bService.getYj(startTime, endTime, yjLevel, null);
            }
            // 查询县级
            else if (yjType == 4) {
                yj = ybba01cService.getYj(startTime, endTime, yjLevel, null);
            }
        }
        // 市级账号
        else if (advcode.endsWith("00")) {
            // 查询全部
            if (yjType == null) {
                // 省级预警
                List<Ybba01bDTO> yjProvince = ybba01aService.getYj(startTime, endTime, yjLevel);
                // 市级预警
                List<Ybba01bDTO> yjCity = ybba01bService.getYj(startTime, endTime, yjLevel, advcode);
                // 县级预警
                String code = advcode.substring(0, 4);
                List<Ybba01bDTO> yjCounty = ybba01cService.getYj(startTime, endTime, yjLevel, code);
                yj.addAll(yjProvince);
                yj.addAll(yjCity);
                yj.addAll(yjCounty);
            }
            // 查询市级
            else if(yjType == 3){
                yj = ybba01bService.getYj(startTime, endTime, yjLevel, advcode);
            }
            // 查询省级预警
            else if (yjType == 2) {
                yj = ybba01aService.getYj(startTime, endTime, yjLevel);
            }
            // 查询县级，本市下的区县
            else if (yjType == 4) {
                String code = advcode.substring(0, 4);
                yj = ybba01cService.getYj(startTime, endTime, yjLevel, code);
            }
        }
        // 县级账号
        else {
            // 查询全部
            if (yjType == null) {
                // 省级预警
                List<Ybba01bDTO> yjProvince = ybba01aService.getYj(startTime, endTime, yjLevel);
                // 市级预警
                String code = advcode.substring(0, 4) + "00";
                List<Ybba01bDTO> yjCity = ybba01bService.getYj(startTime, endTime, yjLevel, code);
                // 县级预警
                List<Ybba01bDTO> yjCounty = ybba01cService.getYj(startTime, endTime, yjLevel, advcode);
                yj.addAll(yjProvince);
                yj.addAll(yjCity);
                yj.addAll(yjCounty);
            }
            // 查询县级
            else if (yjType == 4) {
                yj = ybba01cService.getYj(startTime, endTime, yjLevel, advcode);
            }
            // 查询省级预警
            else if (yjType == 2) {
                yj = ybba01aService.getYj(startTime, endTime, yjLevel);
            }
            // 查询市级，区县直辖市
            else if (yjType == 3) {
                String code = advcode.substring(0, 4) + "00";
                yj = ybba01bService.getYj(startTime, endTime, yjLevel, code);
            }
        }
        Map<String, Integer> maprlt = new HashMap<>();
        Integer dlcount = 0;
        Integer dqcount = 0;
        Integer bluecount = 0;
        Integer yellowcount = 0;
        Integer oragincount = 0;
        Integer redcount = 0;
        for (Ybba01bDTO dto : yj) {
            if (dto.getYbba01b020() == 1) {
                dlcount++;
            } else if (dto.getYbba01b020() == 2) {
                dqcount++;
            }
            if (dto.getYbba01b070() != null && !dto.getYbba01b070().equals("")) {
                redcount++;
            } else if (dto.getYbba01b060() != null && !dto.getYbba01b060().equals("")) {
                oragincount++;
            } else if (dto.getYbba01b050() != null && !dto.getYbba01b050().equals("")) {
                yellowcount++;
            } else {
                bluecount++;
            }
        }
        maprlt.put("allcount", dlcount + dqcount);
        maprlt.put("dlcount", dlcount);
        maprlt.put("dqcount", dqcount);
        maprlt.put("bluecount", bluecount);
        maprlt.put("yellowcount", yellowcount);
        maprlt.put("oragincount", oragincount);
        maprlt.put("redcount", redcount);
        return SysResult.success(yj, maprlt);
    }

    @ApiOperation("预警级别统计")
    @PostMapping("/getWarningLevelStatistics")
    public SysResult getWarningLevelStatistics(Integer dateType, String advcode) {
        if (advcode == null) {
            return SysResult.fail("advcode不能为空");
        }
        Map<String, Object> warningLevelStatistics = new HashMap<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Integer economizeRed = 0;
        Integer economizeOrange = 0;
        Integer economizeYellow = 0;
        Integer economizeBlue = 0;
        // 省级预警
        List<Ybba01a> ybba01aList = ybba01aService.getYbba01aList(dateType);
        if (CollectionUtils.isNotEmpty(ybba01aList)) {
            for (Ybba01a dto : ybba01aList) {
                Map<String, Object> map = new HashMap<>();
                if (dto.getYbba01a070() != null && !dto.getYbba01a070().equals("")) {
                    map.put("area", dto.getYbba01a070());
                    map.put("warningLevel", 1);
                    economizeRed++;
                } else if (dto.getYbba01a060() != null && !dto.getYbba01a060().equals("")) {
                    map.put("area", dto.getYbba01a060());
                    map.put("warningLevel", 2);
                    economizeOrange++;
                } else if (dto.getYbba01a050() != null && !dto.getYbba01a050().equals("")) {
                    map.put("area", dto.getYbba01a050());
                    map.put("warningLevel", 3);
                    economizeYellow++;
                } else {
                    map.put("area", dto.getYbba01a040());
                    map.put("warningLevel", 4);
                    economizeBlue++;
                }
                list.add(map);
            }
        }

        Integer cityRed = 0;
        Integer cityOrange = 0;
        Integer cityYellow = 0;
        Integer cityBlue = 0;
        // 市级预警
        List<Ybba01b> ybba01bList = ybba01bService.getYbba01bList(dateType);
        if (CollectionUtils.isNotEmpty(ybba01bList)) {
            for (Ybba01b dto : ybba01bList) {
                Map<String, Object> map = new HashMap<>();
                if (dto.getYbba01b070() != null && !dto.getYbba01b070().equals("")) {
                    map.put("area", dto.getYbba01b070());
                    map.put("warningLevel", 1);
                    cityRed++;
                } else if (dto.getYbba01b060() != null && !dto.getYbba01b060().equals("")) {
                    map.put("area", dto.getYbba01b060());
                    map.put("warningLevel", 2);
                    cityOrange++;
                } else if (dto.getYbba01b050() != null && !dto.getYbba01b050().equals("")) {
                    map.put("area", dto.getYbba01b050());
                    map.put("warningLevel", 3);
                    cityYellow++;
                } else {
                    map.put("area", dto.getYbba01b040());
                    map.put("warningLevel", 4);
                    cityBlue++;
                }
                list.add(map);
            }
        }


        Integer countyRed = 0;
        Integer countyOrange = 0;
        Integer countyYellow = 0;
        Integer countyBlue = 0;
        // 县级预警
        List<Ybba01c> ybba01cList = ybba01cService.getYbba01cList(dateType);
        if (CollectionUtils.isNotEmpty(ybba01cList)) {
            for (Ybba01c dto : ybba01cList) {
                Map<String, Object> map = new HashMap<>();
                if (dto.getYbba01c070() != null && !dto.getYbba01c070().equals("")) {
                    map.put("area", dto.getYbba01c070());
                    map.put("warningLevel", 1);
                    countyRed++;
                } else if (dto.getYbba01c060() != null && !dto.getYbba01c060().equals("")) {
                    map.put("area", dto.getYbba01c060());
                    map.put("warningLevel", 2);
                    countyOrange++;
                } else if (dto.getYbba01c050() != null && !dto.getYbba01c050().equals("")) {
                    map.put("area", dto.getYbba01c050());
                    map.put("warningLevel", 3);
                    countyYellow++;
                } else {
                    map.put("area", dto.getYbba01c040());
                    map.put("warningLevel", 4);
                    countyBlue++;
                }
                list.add(map);
            }
        }

        Map<String, Integer> redMap = new HashMap<>();
        redMap.put("economize", economizeRed);
        redMap.put("city", cityRed);
        redMap.put("county", countyRed);

        Map<String, Integer> orangeMap = new HashMap<>();
        orangeMap.put("economize", economizeOrange);
        orangeMap.put("city", cityOrange);
        orangeMap.put("county", countyOrange);

        Map<String, Integer> yellowMap = new HashMap<>();
        yellowMap.put("economize", economizeYellow);
        yellowMap.put("city", cityYellow);
        yellowMap.put("county", countyYellow);

        Map<String, Integer> blueMap = new HashMap<>();
        blueMap.put("economize", economizeBlue);
        blueMap.put("city", cityBlue);
        blueMap.put("county", countyBlue);

        Map<String, Object> warningStatistics = new HashMap<>();
        warningStatistics.put("redMap", redMap);
        warningStatistics.put("orangeMap", orangeMap);
        warningStatistics.put("yellowMap", yellowMap);
        warningStatistics.put("blueMap", blueMap);
        warningLevelStatistics.put("warningStatistics", warningStatistics);
        // 按预警级别排序，级别高的靠前
        Collections.sort(list, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                return Integer.compare((Integer) o1.get("warningLevel"), (Integer) o2.get("warningLevel"));
            }
        });
        warningLevelStatistics.put("warningInformation", list);
        return SysResult.success(warningLevelStatistics);
    }

    @ApiOperation("产品查询")
    @PostMapping("/getProduct")
    @ApiImplicitParams({@ApiImplicitParam(name = "yjqcode", value = "产品编号，ybba01b010", required = true, defaultValue = "", dataType = "Integer", paramType = "query")})
    public SysResult getProduct(String yjqcode) {
        if (yjqcode == null) {
            return SysResult.fail("yjqcode不能为空");
        }
        HyDocFile mongoTemplateOne = mongoTemplate.findOne(new Query(
                Criteria.where("id").is(yjqcode)
        ), HyDocFile.class);

        if (mongoTemplateOne == null || mongoTemplateOne.getData() == null) {
            return SysResult.success("暂无文档");
        }
        //保存图片到本地
        String fileSuffix = yjqcode + ".docx";
        String pdffileSuffix = yjqcode + ".pdf";
        if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
            assert mongoTemplateOne != null;
            try {
                Map<String, String> fileMap = minIOUtil.putObject(mongoTemplateOne.getData(), PRODUCT.getPath(), fileSuffix, FileContentType.DOCX);
                //使用Word2PdfUtil将word转换为pdf
                Map<String, String> filePngMap = minIOUtil.putObject(Word2PdfUtil.word2Pdf(fileMap.get("fileUrl")), PRODUCT.getPath(), pdffileSuffix, FileContentType.PDF);
                return SysResult.success(filePngMap.get("fileUrl"));
                //DocxUtil.wordToPdf(filePath, pdffilePath);
            } catch (Exception e) {
                return SysResult.fail("文件上传失败！");
            }

        }
        return SysResult.success(minIOUtil.getFileUrl(PRODUCT.getPath(), pdffileSuffix));
    }

    @ApiOperation("产品查询JPG")
    @PostMapping("/getProductJPG")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yjqcode", value = "产品编号，ybba01b010", required = true, defaultValue = "", dataType = "Integer", paramType = "query")
    })
    public SysResult getProductJPG(String yjqcode) {
        if (yjqcode == null)
            return SysResult.fail("yjqcode不能为空");

        HyImageFile mongoTemplateOne = mongoTemplate.findOne(new Query(
                Criteria.where("id").is(yjqcode)
        ), HyImageFile.class);

        if (mongoTemplateOne == null || mongoTemplateOne.getData() == null) {
            return SysResult.fail("暂无文档");
        }

        //保存图片到本地
        String fileSuffix = yjqcode + ".jpg";
//        String filePath = nginxFilepath + fileSuffix;
//        if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
//            FileUtil.bytesToFile(mongoTemplateOne.getData(), filePath);
//        }
//
//        return SysResult.success(nginxUrl + "/" + fileSuffix);

        if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
            try {
                minIOUtil.putObject(mongoTemplateOne.getData(), GEO_FAC.getPath(), fileSuffix, FileContentType.JPEG);
            } catch (Exception exception) {
                exception.printStackTrace();
                return SysResult.fail("文件上传失败！");
            }

        }
        return SysResult.success(minIOUtil.getFileUrl(GEO_FAC.getPath(), fileSuffix));

    }


    @ApiOperation("地质因子查看")
    @PostMapping("/getGeologicalFactors")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "advcode", value = "", required = true, defaultValue = "", dataType = "String", paramType = "query")
    })
    public SysResult getGeologicalFactors(String advcode) {
        if (StringUtil.IsNullOrEmpty(advcode)) {
            advcode = "370000";
        }
        // 查询行政编码
//        String code = ybab01aService.getCodeById(advcode);
//        if (StringUtil.IsNullOrEmpty(code)){
//            code = "370000";
//        }

        DzPngFile mongoTemplateOne = mongoTemplate.findOne(new Query(
                Criteria.where("advcode").is(advcode)
        ), DzPngFile.class);

        if (mongoTemplateOne == null || mongoTemplateOne.getData() == null
                || mongoTemplateOne.get_id() == null) {
            return SysResult.fail("暂无文档！");
        }

        //保存图片到本地
        String fileSuffix = mongoTemplateOne.get_id() + ".png";

        if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
            try {
                minIOUtil.putObject(mongoTemplateOne.getData(), GEO_FAC.getPath(), fileSuffix, FileContentType.PNG);
            } catch (Exception exception) {
                exception.printStackTrace();
                return SysResult.fail("文件上传失败！");
            }

        }
        return SysResult.success(minIOUtil.getFileUrl(GEO_FAC.getPath(), fileSuffix));

    }

    @ApiOperation("产品发布")
    @PostMapping("/FbProduct")
    public SysResult FbProduct(String advcode) {
        if (advcode == null)
            return SysResult.fail("advcode不能为空");
        if (advcode.endsWith("0000")) {
            Ybba02a ybba02a = ybba02aService.getProductone();
            return SysResult.success(ybba01aService.FbProduct(ybba02a));
        } else if (advcode.endsWith("00")) {
            Ybba02b ybba02b = ybba02bService.getProductone(advcode);
            return SysResult.success(ybba01bService.FbProduct(ybba02b));
        } else {
            Ybba02c ybba02c = ybba02cService.getProductone(advcode);
            return SysResult.success(ybba01cService.FbProduct(ybba02c));
        }
    }

    @ApiOperation("生成产品")
    @PostMapping("/createProduct")
//    public SysResult createProduct(Integer issueNum,
    public Object createProduct(Integer issueNum,
                                String userName,
                                String yjType,
                                String sXType,
                                String date,
                                String timeChar,
                                Integer nTimes,
                                String colorAndPos,
                                String posStr,
                                MultipartFile[] images,
                                String layerName,
                                String dlData,
                                Integer type, String point) throws Exception {
        return dqyjService.createProduct(
                issueNum, userName, yjType, sXType, date, timeChar, nTimes, colorAndPos,
                posStr, images, layerName, dlData, type, point);
    }

    @ApiOperation("生成产品")
    @PostMapping("/createProduct1")
//    public SysResult createProduct(Integer issueNum,
    public Object createProduct1(Integer issueNum,
                                 String userName,
                                 String yjType,
                                 String sXType,
                                 String date,
                                 String timeChar,
                                 Integer nTimes,
                                 String colorAndPos,
                                 String posStr,
                                 MultipartFile[] images,
                                 String layerName,
                                 String dlData,
                                 Integer type, String point) throws Exception {
        return dqyjService.createProduct1(
                issueNum, userName, yjType, sXType, date, timeChar, nTimes, colorAndPos,
                posStr, images, layerName, dlData, type, point);
    }

    @ApiOperation("生成产品")
    @PostMapping("/createProduct2")
//    public SysResult createProduct(Integer issueNum,
    public Object createProduct2(Integer issueNum,
                                 String userName,
                                 String yjType,
                                 String sXType,
                                 String date,
                                 String timeChar,
                                 Integer nTimes,
                                 String colorAndPos,
                                 String posStr,
                                 MultipartFile[] images,
                                 String layerName,
                                 String dlData,
                                 Integer type, String point) throws Exception {
        return dqyjService.createProduct2(
                issueNum, userName, yjType, sXType, date, timeChar, nTimes, colorAndPos,
                posStr, images, layerName, dlData, type, point);
    }

    @ApiOperation("地理分析")
    @PostMapping("/multiplePosDlfx")
    //, @RequestBody String xzbm
    public SysResult MultiplePosDlfx(@NotNull @RequestBody MultiplePosDlfxDto2 multiplePosDlfxDto) throws UnsupportedEncodingException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        String xzbm = multiplePosDlfxDto.getXzbm();
        List<List<List<Double>>> posList = multiplePosDlfxDto.getPosList();
        List<LayerRcoDto> layerRcoDtoList = new ArrayList<>();
        for (List<List<Double>> pos : posList) {
            DlfxDto dlfxDto = new DlfxDto();
            dlfxDto.setLayerName(multiplePosDlfxDto.getLayerName());
            dlfxDto.setPos(pos);
            List<LayerRcoDto> layerRcoDtos1 = yjfwService.listLayerByScope(dlfxDto, xzbm);
            layerRcoDtoList.addAll(layerRcoDtos1);
        }
        List<LayerRcoDto> distinctLayerRcoDtoList = layerRcoDtoList.stream().distinct().collect(Collectors.toList());
        return SysResult.success(distinctLayerRcoDtoList);
    }

    @ApiOperation("网络请求资源")
    @PostMapping("/getImg")
    public byte[] getResource(String localResource) {

        String filePath = "D:/dmgisqt1.1/program/DmCloudService/PluginLibrary/temp/" + localResource;
        String resource = filePath;
        List<Byte> resource2 = new ArrayList<>();
        if (new File(resource).exists()) {
            try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get(resource)))) {
                byte[] buff = new byte[1024];
                int len;
                while ((len = bis.read(buff)) != -1) {
                    for (int i = 0; i < len; i++) {
                        resource2.add(buff[i]);
                    }
                }
                return Bytes.toArray(resource2);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    @ApiOperation("zdyhd")
    @GetMapping("/zdyhd")
    public SysResult selectYhd() throws IOException, UnirestException {
        Unirest.setTimeouts(0, 0);
        HttpResponse<String> response = Unirest.post("https://dzfz.hnzrzy.cn/dmgispt/dmgis_dcpj/zhcx/queryZhcxZhd")
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .field("anum", "1000")
                .field("zhdType", "")
                .field("cxtypes", "")
                .field("keyPoint", "12")
                .field("city", "4312")
                .field("years", "2024")
                .field("divcode", "431200")
                .asString();
        String jsonResponse = response.getBody();
        return SysResult.success(jsonResponse);
    }


    public static double dmsToLl(String dms) {
        double ds = Double.parseDouble(dms);
        if (ds > 180) {
            int dd = (int) (ds / 10000);
            int ff = (int) ((ds - dd * 10000) / 100);
            int mm = (int) (ds - dd * 10000 - ff * 100);
            ds = dd + ff / 60.00 + mm / 3600.00;

        }
        return ds;
    }

    @ApiOperation("等值图")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "satrTime", value = "开始时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", dataType = "String", required = true),
            @ApiImplicitParam(name = "elementType", value = "类型，参考：12小时雨量\n" +
                    "24小时雨量\n" +

                    "6小时雨量\n" +

                    "1小时雨量\n" +

                    "3小时雨量\n"

                    , dataType = "String", required = true)
    })
    @PostMapping("/coutView")
    public SysResult coutView(String satrTime, String elementType, String endTime) throws IOException, ParseException {
        String type = "实况";//预报
        //String satrTime ="2023-11-15 10:00:00";
        //String endTime="2023-11-23 16:00:00";
        SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date satrdate = dateFormat2.parse(satrTime);
        Date enddate = dateFormat2.parse(endTime);
        List<MsgDto> msgMediumSmallScaleList = new ArrayList<>();
        switch (type) {

            case "实况":
//                QueryWrapper<Qxaa01a> Wrapper = new QueryWrapper<>();
//                Wrapper.between("qxaa01a050",satrdate,enddate).eq("qxaa01a030","怀化市");
                List<Qxaa01a> qxaa01aList = qxaa01aMapper.selectList6(satrTime, endTime);
                for (Qxaa01a qxaa01a : qxaa01aList) {
                    msgMediumSmallScaleList.add(new MsgDto(qxaa01a.getQxaa01a070(), qxaa01a.getQxaa01a080(), qxaa01a.getQxaa01a100()));
                }
                break;
            case "预报":
                break;
        }
//        List<MsgDto> msgMediumSmallScaleList = JSON.parseArray(msgListstr, MsgDto.class);
        List<ContourSetting> contourSettingList = riskManagementMapper.queryByElementType(elementType);
        StringBuilder txt = new StringBuilder();
        // 添加基本参数
        txt.append("[基本参数]\n");
        //点的个数
        txt.append(msgMediumSmallScaleList.size()).append(",");
        //分级数
        txt.append(contourSettingList.size()).append(",");
        //服务名
        txt.append(serveName + ",1,1.5,5,1,0,0,1\n");
        // 添加数据
        txt.append("[数据]\n");
        msgMediumSmallScaleList.forEach(longitudeLatitudeValue -> {
            txt.append(longitudeLatitudeValue.getLongitude()).append("\t")
                    .append(longitudeLatitudeValue.getLatitude()).append("\t")
                    .append(longitudeLatitudeValue.getValue()).append("\n");
        });
        // 添加分级参数
        txt.append("[分级参数]\n");
        contourSettingList.forEach(contourSetting -> {
            txt.append(contourSetting.getElementValue()).append(",")
                    .append(contourSetting.getElementColor()).append(",")
                    .append(contourSetting.getElementColor()).append(",")
                    .append("1,0,")
                    .append(contourSetting.getElementColor()).append(",")
                    .append("0,0,0,0").append("\n");
        });
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 生成文件名，格式为时间+RefinedForecastingController
        String txtName = dateFormat.format(new Date()) + "-" + "1hourain";

        String txtPath = txtFileManager.writeDataToTxtFile(txt.toString(), txtName);
        //文件夹目录
        String homePath = TxtFileManager.extractFolderPath(txtPath);
        // 一小时删除任务
        TxtFileManager.cleanupTempFiles(homePath, 3600000);

        System.err.println("文件存储路径：" + txtPath);
        String url = "http://" + dmgisIp + ":" + txtPort + "/common/files/" + txtName + ".txt";
        System.err.println(url);

        DmServiceConnector conn = new DmServiceConnector(dmgisIp, dmgisPort);
        String uniqueno = conn.getCallPlugin(pluginClassFullName, methodName, "GetInterpolationWork|" + url);
        System.err.println(uniqueno);
        String imgname = conn.getCallPlugin(pluginClassFullName, methodName, "GetContourPic|" + uniqueno + "|" + serveName + "|500|500|" + rect + "|1");
        Map<String, String> rlt = new HashMap<>();
        rlt.put("imgurl", imgname);
        rlt.put("rect", rect);
        return SysResult.success(rlt);
    }


    //file:///D:/8-21修改/hndz/dmgisqt1.1/program/DmCloudService/PluginLibrary/temp/20240625171906.png
    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<Resource> downloadFile2(@PathVariable String filename) {
        try {
            String[] folders = filename.split("/");
            String actualFilename = folders[folders.length - 1];
            String ur = "file:///" + txtFile.replace("\\", "/") + "/" + filename;
            URI url = new URI(ur);
            Resource resource = new UrlResource(url);

            if (resource.exists() && resource.isReadable()) {
                HttpHeaders headers = new HttpHeaders();
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + actualFilename);
                return ResponseEntity.ok().headers(headers).body(resource);
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
            }
        } catch (MalformedURLException | URISyntaxException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
        }
    }


    @DS("slave_qxdata")
    @ApiOperation("图层管理-专题图")
    @GetMapping("/ztlayertree")
    public SysResult ztlayertree(String advcode) {
        if (advcode == null)
            return SysResult.fail("advcode为空");
        if (advcode.endsWith("0000")) {
            advcode = advcode.substring(0, 2);
        } else if (advcode.endsWith("00")) {
            advcode = advcode.substring(0, 4);
        }
        List<Zhaa03b> list = zhaa03bService.ztlayertree(advcode);
        return SysResult.success(list);
    }

    @DS("slave_qxdata")
    @ApiOperation("图层管理-新增图层")
    @PostMapping("/addLayer")
    public SysResult addLayer(@RequestBody Zhaa03b zhaa03b) {
        try {
            int affectNum = zhaa03bService.addLayer(zhaa03b);
            return SysResult.success(affectNum);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("图层管理-修改图层")
    @PostMapping("/updateLayer")
    public SysResult updateLayer(@RequestBody Zhaa03b zhaa03b) {
        try {
            int affectNum = zhaa03bService.updateLayer(zhaa03b);
            return SysResult.success(affectNum);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("图层管理-删除图层")
    @GetMapping("/deleteLayer")
    public SysResult deleteLayer(String id) {
        try {
            int affectNum = zhaa03bService.deleteLayer(id);
            return SysResult.success(affectNum);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("采集信息查询")
    @GetMapping("/getQxda02aInfo")
    public SysResult getQxda02aInfo() {
        try {
            List<Qxda02a> result = qxda02aService.getQxda02aInfo();
            return SysResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("采集信息修改")
    @PostMapping("/updateQxda02aInfo")
    public SysResult updateQxda02aInfo(@RequestBody List<Qxda02aVo> qxda02aVoList) {
        try {
            int affectNum = qxda02aService.updateQxda02aInfo(qxda02aVoList);
            return SysResult.success(affectNum);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("数据采集监控")
    @PostMapping("/dataAcquisitionMonitoring")
    public SysResult dataAcquisitionMonitoring(@RequestBody DataAcquisitionMonitoringInVo dataAcquisitionMonitoringInVo) {
        try {
            List<Qxdd01a> result = qxdd01aService.dataAcquisitionMonitoring(dataAcquisitionMonitoringInVo);
            return SysResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("数据采集监控-获取监控类型")
    @GetMapping("/getDataAcquisitionType")
    public SysResult getDataAcquisitionType() {
        try {
            List<Map> result = qxdd01aService.getDataAcquisitionType();
            return SysResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @DS("slave_qxdata")
    @ApiOperation("数据采集监控-获取监控名称")
    @GetMapping("/getDataAcquisitionName")
    public SysResult getDataAcquisitionName() {
        try {
            List<Map> result = qxdd01aService.getDataAcquisitionName();
            return SysResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    //TODO 插件图片生成未完成，等到后续再完善`
    @ApiOperation("雨情报告Word生成")
    @PostMapping("generateRainfallReport")
    public SysResult generateRainfallReport(@RequestBody RainfallReportInVo rainfallReportInVo) {
        try {
            String result = yqService.generateRainfallReport(rainfallReportInVo);
            return SysResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    @ApiOperation("预警产品图片下载")
    @PostMapping("warningProductsDownload")
    public SysResult warningProductsDownload(String yjqcode) {
        try {
            String result = yqService.warningProductsDownload(yjqcode);
            return SysResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return SysResult.fail(e.getMessage());
        }
    }

    // 需要做权限划分
    @ApiOperation("预警灾害类型统计")
    @PostMapping("/disasterTypeStatistics")
    public SysResult disasterTypeStatistics() {
        return SysResult.success(ybba01aService.disasterTypeStatistics());
    }


    @ApiOperation("根据行政编码查询预警插件")
    @PostMapping("/selectWarningPlugin")
    public SysResult selectWarningPlugin(String code) {
        String name = yqService.selectWarningPlugin(code);
        if (StringUtil.IsNullOrEmpty(name)) {
            // 默认济南市
            return SysResult.success("jncity");
        }
        return SysResult.success(name);
    }

    @ApiOperation("查询模型训练数据")
    @GetMapping("/getModelTrainingData")
    public SysResult getModelTrainingData(String startTime, String endTime) {
        return SysResult.success(ybca02aService.getModelTrainingData(startTime, endTime));
    }

    @ApiOperation("预警区灾害类型统计")
    @PostMapping("/yjDisasterTypes")
    public SysResult yjDisasterTypes(@RequestBody YjDisasterTypes yjDisasterTypes) {
        return SysResult.success(zdda01aService.dzTable(yjDisasterTypes.getPoint(), yjDisasterTypes.getCode()));
    }

    @ApiOperation("查询灾害点经纬度")
    @GetMapping("/getDisasterList")
    public SysResult getDisasterList(String code, String type) {
        return SysResult.success(zdda01aService.getDisasterList(code, type));
    }

}
